package com.jinzhi.jinzhidata.util;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class WXHelper {

    //微信参数
    private static String accessToken;
    private static String jsApiTicket;
    //获取参数的时刻
    private static Long getTicketTime = 0L;
    private static Long getTokenTime = 0L;
    //参数的有效时间,单位是秒(s)
    private static Long tokenExpireTime = 0L;
    private static Long ticketExpireTime = 0L;

    public static Map<String, String> getWXOpenidAndToken(String code) {
        if (StringUtils.isEmpty(code)) {
            return null;
        }
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + Constant.WX_APPID + "&secret=" + Constant.WX_SECRET + "&code=" + code + "&grant_type=authorization_code ";
        String result = Client.httpRequest(url, "GET", null);
        return getMap(result, new String[]{"access_token", "openid"});
    }

    public static Boolean verityToken(String access_token, String openid) {
        if (StringUtils.isEmpty(access_token) || StringUtils.isEmpty(openid)) {
            return null;
        }
        String url = "https://api.weixin.qq.com/sns/auth?access_token=" + access_token + "&openid=" + openid;
        String result = Client.httpRequest(url, "GET", null);
        Map<String, String> map = getMap(result, new String[]{"errcode", "errmsg"});
        if (null == map || map.isEmpty()) {
            return false;
        }
        if (map.get("errcode").equals("0") && map.get("errmsg").equals("ok")) {
            return true;
        }
        return false;
    }

    public static Map<String, String> getWXUserInfo(String access_code, String openid) {
        if (StringUtils.isEmpty(access_code) || StringUtils.isEmpty(openid)) {
            return null;
        }
        String url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_code + "&openid=" + openid + "&lang=zh_CN";
        String result = Client.httpRequest(url, "GET", null);
        return getMap(result, new String[]{"openid", "nickname", "sex", "province", "city", "country", "headimgurl"});
    }

    public static String getJsApiTicket() {
        //判断accessToken是否已经存在或者token是否过期
        if (StringUtils.isEmpty(accessToken) || (System.currentTimeMillis() - getTokenTime > tokenExpireTime * 1000)) {
            String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + Constant.WX_APPID + "&secret=" + Constant.WX_SECRET;
            String result = Client.httpRequest(url, "GET", null);
            Map<String, String> tokenInfo = getMap(result, new String[]{"access_token", "expires_in"});
            if (null == tokenInfo || tokenInfo.isEmpty()) {
                return null;
            }
            accessToken = tokenInfo.get("access_token");
            tokenExpireTime = Long.valueOf(tokenInfo.get("expires_in"));
            getTokenTime = System.currentTimeMillis();
        }
        //判断jsApiTicket是否已经存在或者是否过期
        if (StringUtils.isEmpty(jsApiTicket) || (System.currentTimeMillis() - getTicketTime > ticketExpireTime * 1000)) {
            String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + accessToken + "&type=jsapi";
            String result = Client.httpRequest(url, "GET", null);
            Map<String, String> ticketInfo = getMap(result, new String[]{"ticket", "expires_in"});
            if (null == ticketInfo || ticketInfo.isEmpty()) {
                return null;
            }
            jsApiTicket = ticketInfo.get("ticket");
            ticketExpireTime = Long.valueOf(ticketInfo.get("expires_in"));
            getTicketTime = System.currentTimeMillis();
        }
        return jsApiTicket;
    }

    public static Map<String, String> getJsApiConfig(String url, String jsapi_ticket, String nonceStr, String timestamp) {
        String str = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + nonceStr + "&timestamp=" + timestamp + "&url=" + url;
        String signature = SHA.getSHA1(str);
        Map<String, String> config = new HashMap<>();
        config.put("url", url);
        config.put("jsapi_ticket", jsapi_ticket);
        config.put("nonceStr", nonceStr);
        config.put("timestamp", timestamp);
        config.put("signature", signature);
        config.put("appid", Constant.WX_APPID);
        return config;
    }

    private static Map<String, String> getMap(String result, String[] args) {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode jsonNode;
        try {
            jsonNode = mapper.readTree(result);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        if (null == jsonNode) {
            return null;
        }
        Map<String, String> m = new HashMap<>();
        for (String name : args) {
            JsonNode node = jsonNode.findValue(name);
            if (null == node) {
                return null;
            }
            m.put(name, node.asText());
        }
        return m;
    }
}
